#pragma once

#include <sys/epoll.h>

#include "Logger.hpp"

using namespace LogMudule;

class Epoller
{
    static const int default_fd = -1;

public:
    Epoller()
        : _epollfd(default_fd)
    {
    }
    bool Init()
    {
        // 创建epoll模型
        int n = epoll_create(256);
        if (n > 0)
        {
            LOG(LogLevel::DEBUG) << "epoll模型创建成功,epollfd: " << n;
            _epollfd = n;
            return true;
        }
        else
        {
            LOG(LogLevel::ERROR) << "epoll模型创建失败";
            return false;
        }
    }
    int Wait(struct epoll_event* events,int size,int timeout)
    {
        return epoll_wait(_epollfd,events,size,timeout);
    }
    bool Add(const int fd, uint32_t e)
    {
        struct epoll_event event;
        event.data.fd=fd;
        event.events=e;


        int n=epoll_ctl(_epollfd, EPOLL_CTL_ADD, fd, &event);
        if(n==0)
        {
            LOG(LogLevel::DEBUG) << "添加新的fd到epoll模型--成功--,fd: " <<fd;
        }
        else
        {
            perror("Epoll.hpp 52: ");
            LOG(LogLevel::WARNING) << "添加新的fd到epoll模型--失败--,fd: "<<fd;
            return false;
        }
        return true;
    }
    bool Delete(const int fd)
    {
        int n=epoll_ctl(_epollfd, EPOLL_CTL_DEL, fd, nullptr);
        if(n==0)
        {
            LOG(LogLevel::DEBUG) << "把fd从epoll模型删除--成功--,fd: " <<fd;
        }
        else
        {
            LOG(LogLevel::WARNING) << "把fd从epoll模型删除--失败--,fd: "<<fd;
            return false;
        }
        return true;
    }
    bool Modify(const int fd,uint32_t e)
    {
        struct epoll_event event;
        event.data.fd=fd;
        event.events=e;

        int n=epoll_ctl(_epollfd, EPOLL_CTL_MOD, fd, &event);
        if(n==0)
        {
            LOG(LogLevel::DEBUG) << "修改fd关心的事件--成功--,fd: " <<fd;
        }
        else
        {
            LOG(LogLevel::WARNING) << "修改fd关心的事件--失败--,fd: "<<fd;
            return false;
        }
        return true;
    }
    ~Epoller()
    {
        close(_epollfd);
    }

private:
    int _epollfd;
};
